package com.mxchip.livestar.rest.log;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class OKHTTP {
    private boolean DEBUG = false; //Utils.isDebug();
    private static OKHTTP okhttp = new OKHTTP();

    public static OKHTTP getInstance() {
        return okhttp;
    }


    public Retrofit build() {
        return init().build();

    }

    public Retrofit.Builder init() {

        OkHttpClient okHttpClient = newBuild();
        Retrofit.Builder mBuilder = new Retrofit.Builder().client(okHttpClient);
        mBuilder.baseUrl("http://139.199.34.119:8889/");
        mBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        mBuilder.addConverterFactory(GsonConverterFactory.create());
        return mBuilder;
    }

    private OkHttpClient newBuild() {
        return new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                //允许失败重试
                .retryOnConnectionFailure(true)
                .addInterceptor(createLogInterceptor())
                .build();

    }


    //log 拦截器
    private HttpLoggingInterceptor createLogInterceptor() {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        if (DEBUG) {
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
        }
        return logInterceptor;
    }

    public <T> T create(Class<T> clazz) {
        return build().create(clazz);

    }
}
